package de.karlNet.login;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapModel.LdapObject;

@Controller
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class LdapUsernameLookup {
	@Autowired
	private LdapTemplate ldapTemplate;
	@Value("${ldap.baseDN}")
	protected String baseDN;
	@Autowired
	private AttributeObjectMapper attributeObjectMapper;

	public String lookupDN(String username) {
		@SuppressWarnings("rawtypes")
		List ldapObjects = this.ldapTemplate.search(this.baseDN,
				"(samaccountname=" + username + ")", attributeObjectMapper);
		if (ldapObjects.size() > 0) {
			return ((LdapObject) (ldapObjects.get(0))).getDn().toLowerCase();
		} else {
			return null;
		}
	}
}
